package cn.tedu.charging.user.service.impl;

import cn.tedu.charging.common.pojo.utils.JsonUtils;
import cn.tedu.charging.user.dao.repository.UserRepository;
import cn.tedu.charging.user.pojo.po.UserPO;
import cn.tedu.charging.user.pojo.vo.WxLoginData;
import cn.tedu.charging.user.service.WXLoginService;
import com.alibaba.nacos.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class WXLoginServiceImpl implements WXLoginService {
    private String appId="wx717347c63abcb748";
    private String appSecret="39245cc581891c79f55421f274276dd8";

    @Autowired
    private UserRepository userRepository;

    @Override
    public Integer login(String code, String nickName) {
        String openId = getOpenId(code);
        UserPO userPO=userRepository.getUserByOpenId(openId);
        if (userPO != null) {
            return userPO.getId();
        }else {
            return userRepository.saveUser(openId, nickName);
        }

    }

    private String getOpenId(String code) {
        //通过微信的接口地址和appidAppID(小程序ID)和 appSecret AppSecret(小程序密钥)
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + appId +
                "&secret=" + appSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";
        //利用spring原生http请求工具对接口进行请求
        RestTemplate restTemplate = new RestTemplate();
        String jsonData = restTemplate.getForObject(url, String.class);
        log.debug("调用微信地址获取用户信息:{}",jsonData);
        WxLoginData wxLoginData = JsonUtils.fromJson(jsonData, WxLoginData.class);
        //返回结果
        //{"session_key":"eyYhTlvXQ6L+uTgwRuk6hA==",
        // "openid":"o8qfb6Kor2EIEg-7h4nkquviUMQA"}
        //openid 就是微信来确定唯一用户的

        //String openid = jsonData.getString("openid");
        if (jsonData != null && StringUtils.isNotBlank(wxLoginData.getOpenid())) {
            return wxLoginData.getOpenid();
        }
        return "";
    }
}
